package com.arelikebrothers.demo.algorithm.basic.analysis;

/**
 * Created by lennon on 17/06/2017.
 */
public class MyQueue {
    private int capacity = 0;
    private int[] data;

    private int front;
    private int rear;

    public MyQueue(int capacity) {
        this.capacity = capacity;
        this.data = new int[capacity + 1];
        this.capacity++;
    }


    public void enqueue(int val) {
        if (full()) {
            throw new IndexOutOfBoundsException("Queue is full");
        }
        rear = (rear + 1) % capacity;
        data[rear] = val;
    }

    public int dequeue() {
        if (empty()) {
            throw new IndexOutOfBoundsException("Queue is empty");
        }
        front = (front + 1) % capacity;
        return data[front];
    }

    private boolean empty() {
        return front == rear;
    }

    public boolean full() {
        if (size() == capacity - 1) {
            return true;
        }
        return false;
    }

    public int size() {
        return (capacity + rear - front) % capacity;
    }

    public static void main(String[] args) {
        MyQueue queue = new MyQueue(5);

        for (int i = 0; i < 5; i++) {
            queue.enqueue(i);
            System.out.println(queue.size());
        }

        for (int i = 0; i < 6; i++) {
            int val = queue.dequeue();
            System.out.println(queue.size());
        }
    }
}
